import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import grails.converters.*

class FilesController {

    def index = {redirect(action:list, params:params)}

    def allowedMethods = [upload:'POST']

    def list = {
        def cmsId = params.cms
        def dir = params.dir?:""
        println "${cmsId} - ${dir}"

        dir = dir.replaceAll("\\.\\./","")
        println "${cmsId} - ${dir}"

        String configDir = grailsApplication.config.cmsdata.dir

        String target = configDir + cmsId + dir
        println "target - ${target}"

        def files = []
        File d = new File(target)
        if (d.exists() && d.isDirectory()){
            files = d.listFiles()
        }

        [files:files, dirName:dir]
    }

    def show = {
    }

    def doit = {
    }

    def dir = {
        def cmsId = params.cms
        def dir = params.dir?:"/"
        println "${cmsId} - ${dir}"

        dir = dir.replaceAll("\\.\\./","")
        println "Modified dir: ${cmsId} - ${dir}"

        String configDir = grailsApplication.config.cmsdata.dir

        String target = configDir + cmsId + dir
        println "target - ${target}"

        def files = []
        File d = new File(target)
        if (d.exists() && d.isDirectory()){
            files = d.listFiles()
        }

        response.setHeader("Cache-Control", "no-store")
        render(contentType: "text/json") {
            nodes {
                for (f in files) {
                    node(name: f.name, isDir: f.isDirectory())
                }
            }
        }
    }

    def upload = {
        def cmsId = params.cms
        def dir = params.dir?:""

        dir = dir.replaceAll("\\.\\./","")        
        println "${cmsId} - ${dir}"

        if (!(request instanceof MultipartHttpServletRequest)){
            throw new Exception("No Multipart")
        }

        def multiRequest = (MultipartHttpServletRequest)request

        CommonsMultipartFile f = (CommonsMultipartFile)multiRequest.getFile("theFile")
        
        String configDir = grailsApplication.config.cmsdata.dir

        println "${cmsId} - ${dir}"
        println f.getOriginalFilename()
        println f.getContentType()

        String target = "${configDir}/${cmsId}/${dir}/${f.originalFilename}"

        println "${target}"

        if (!f.empty){
            f.transferTo(new File(target))
            flash.message = "Successfully uploaded file: ${f.originalFilename}"
        } else {
            flash.message = "File cannot be empty"
        }
        redirect(uri:"/${params.cms}/files/list?dir=${dir}")
    }

    def delete = {
        def filename = params.filename
        def dir = params.dir
        def cmsId = params.cms

        String configDir = grailsApplication.config.cmsdata.dir

        String target = "${configDir}/${cmsId}/${dir}/${filename}"

        File f = new File(target)
        if (f.exists()){
            f.delete()
            flash.message = "Successfully deleted file: ${filename}"
        } else {
            flash.message = "File does not exist"
        }
        redirect(uri:"/${params.cms}/files/list?dir=${dir}")
    }
}
